
#import "CYTLVTWO_MainWebVC.h"
#import <WebKit/WebKit.h>
#import <AdSupport/AdSupport.h>

@interface CYTLVTWO_MainWebVC ()<WKScriptMessageHandler, WKNavigationDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIView *loadingBg;
@end

#define IPHONE_X \
({BOOL isPhoneX = NO;\
if (@available(iOS 11.0, *)) {\
isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\
}\
(isPhoneX);})

@implementation CYTLVTWO_MainWebVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    [self loadWkwebviewconfig];
    [self loadWebUrl];
}

-(void)loadWkwebviewconfig
{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.preferences = [[WKPreferences alloc] init];
    config.preferences.minimumFontSize = 10;
    config.preferences.javaScriptEnabled = YES;
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    config.processPool = [[WKProcessPool alloc]init];
    config.userContentController = [[WKUserContentController alloc] init];
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    self.webView.backgroundColor = [UIColor blackColor];
    self.webView.scrollView.backgroundColor = [UIColor blackColor];
    if(@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.view addSubview:self.webView];
    
    CGFloat fringeHeight = self.fringeStatus==1 ? 44 : 0;
    CGFloat bottomBarHeight = self.bottomBarStatus==1 ? 34 : 0;
    if ([self.screenType intValue]==1) {
        bottomBarHeight = self.fringeStatus==1 ? 34 : 0;
    }
    CGFloat leftDistance = self.bottomBarStatus==1 ? 15 : 0;
    
    UIEdgeInsets screenEdge;
    if ([self.screenType intValue]==2) {
        screenEdge = UIEdgeInsetsMake(fringeHeight, 0, bottomBarHeight, 0);
    } else {
        screenEdge = UIEdgeInsetsMake(0, fringeHeight, leftDistance, bottomBarHeight);
    }
    
    if (!IPHONE_X) {
        screenEdge = UIEdgeInsetsZero;
    }
    
    [self.webView setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSLayoutConstraint *topCos = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:screenEdge.top];
    NSLayoutConstraint *leftCos = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:screenEdge.left];
    NSLayoutConstraint *bottomCos = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-screenEdge.bottom];
    NSLayoutConstraint *rightCos = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:-screenEdge.right];
    [self.view addConstraints:@[topCos,leftCos,bottomCos,rightCos]];
    
    self.webView.navigationDelegate = self;
    
}

- (void)loadWebUrl {
    
    [self.view addSubview:self.loadingBg];
    [self.loadingBg setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSLayoutConstraint *xCox = [NSLayoutConstraint constraintWithItem:self.loadingBg attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    NSLayoutConstraint *yCox = [NSLayoutConstraint constraintWithItem:self.loadingBg attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    NSLayoutConstraint *widthCox = [NSLayoutConstraint constraintWithItem:self.loadingBg attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:35];
    NSLayoutConstraint *heightCox = [NSLayoutConstraint constraintWithItem:self.loadingBg attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:35];
    [self.view addConstraints:@[xCox,yCox,widthCox,heightCox]];
    
    
    self.webView.hidden = YES;
    NSString *urlLinStr = [_linkUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlLinStr];
    if (self.needIdfa) {
        url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlLinStr, [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]]];
    } else {
        url = [NSURL URLWithString:urlLinStr];
    }
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    [_webView loadRequest:request];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *urlstr = navigationAction.request.URL.absoluteString;
    
    BOOL isJump = NO;
    for (NSString *host in self.jumpHosts) {
        if ([urlstr hasPrefix:host]) {
            isJump = YES;
        }
    }
    
    if ([urlstr hasPrefix:[[NSString alloc] initWithFormat:@"%@%@%@",@"w",@"ei",@"xin"]] || [urlstr hasPrefix:[[NSString alloc] initWithFormat:@"%@%@%@",@"a",@"lip",@"ay"]] || [urlstr hasPrefix:[[NSString alloc] initWithFormat:@"%@%@q",@"m",@"q"]] || isJump) {
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL options:@{} completionHandler:nil];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    
 [self performSelector:@selector(showWebView) withObject:self afterDelay:0.5];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [self.loadingBg removeFromSuperview];
}
- (void)showWebView{
    self.webView.hidden = NO;
    [self.loadingBg removeFromSuperview];
}


- (UIView *)loadingBg{
    if (!_loadingBg) {
        UIView *loadingBg = [UIView new];
        loadingBg.backgroundColor = [UIColor clearColor];
        UIActivityIndicatorView *actV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [loadingBg addSubview:actV];
        
        [actV setTranslatesAutoresizingMaskIntoConstraints:NO];
        
        NSLayoutConstraint *xCox = [NSLayoutConstraint constraintWithItem:actV attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:loadingBg attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
        NSLayoutConstraint *yCox = [NSLayoutConstraint constraintWithItem:actV attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:loadingBg attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
        [loadingBg addConstraints:@[xCox,yCox]];
        
        [actV startAnimating];
        _loadingBg = loadingBg;
    }
    return _loadingBg;
}

// 设备支持方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if ([self.screenType intValue] == 1) {
        return UIInterfaceOrientationMaskLandscapeRight;
    }else {
        return UIInterfaceOrientationMaskPortrait;
    }
    
}

//- (BOOL)shouldAutorotate {
//    return YES;
//}
@end


